<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>音频可视化</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      #fileChooser {
        position: absolute;
        left: 50%;
      }
      #canvas {
        margin-left: 5px;
        border: 1px solid red;
      }
    </style>
  </head>
  <body>
    <input id="fileChooser" type="file" />
    <audio id="audio" src="./江湖一笑.mp3" controls></audio>
    <canvas id="canvas" width="800" height="600"></canvas>
    <script>
      const AudioContext = window.AudioContext || window.webkitAudioContext;
      const audioContext = new AudioContext();
      let analyser = audioContext.createAnalyser();
      analyser.fftSize = 256;
      analyser = audioContext.createAnalyser();

      const audio = document.getElementById("audio");
      const audioSrc = audioContext.createMediaElementSource(audio);
      audioSrc.connect(analyser);
      analyser.connect(audioContext.destination);

      const canvas = document.getElementById("canvas");
      const ctx = canvas.getContext("2d");
      ctx.lineWidth = 2;

      const grd = ctx.createLinearGradient(0, 0, 600, 0);
      grd.addColorStop(0, "#00d0ff");
      grd.addColorStop(1, "#eee");

      const grd2 = ctx.createLinearGradient(0, 0, 600, 0);
      grd2.addColorStop(0, "#fff");
      grd2.addColorStop(1, "#e720ee");

      const het = 5;
      let animateId;
      function render() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        const dataArray = new Uint8Array(analyser.frequencyBinCount);
        analyser.getByteFrequencyData(dataArray);

        ctx.beginPath();

        for (let i = 0; i < window.innerWidth; i++) {
          const value = dataArray[6 * i];

          // 上柱子
          ctx.fillStyle = grd;
          ctx.fillRect(i * 5, 300, 2, -value + 1);
          ctx.fillRect(i * 5, 280 - value, 2, het);

          // 下柱子
          ctx.fillStyle = grd2;
          ctx.fillRect(i * 5, 300, 2, value + 1);
          ctx.fillRect(i * 5, 320 + value, 2, het);
        }

        animateId = requestAnimationFrame(render);
      }
      animateId = requestAnimationFrame(render);

      document.getElementById("fileChooser").onchange = (e) => {
        if (e.target.files[0]) {
          const playfile = URL.createObjectURL(e.target.files[0]);
          audio.src = playfile;
          const musicName = e.target.files[0].name.split(".")[0];
          audio.play();
        }
      };
    </script>
  </body>
</html>
